package com.yjz.common.restful

import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.ConcurrentHashMap

/**
 *作用 :
 *作者 : yjz
 *时间 : 2025/2/11 11:02
 */
class ZRestFul(val baseUrl: String, call: JCall.Factory) {
    // 存储请求的方法
    private var methodService: ConcurrentHashMap<Method, MethodParser> = ConcurrentHashMap();

    // 存储拦截器
    private var interceptors: MutableList<Interceptor> = mutableListOf()

    // 调度器，用于转换构建真正的请求方法
    private var scheduler: Scheduler? = null;

    init {
        scheduler = Scheduler(call, interceptors)
    }

    fun addInterceptor(interceptor: Interceptor) {
        interceptors.add(interceptor)
    }

    @Suppress("UNCHECKED_CAST")
    fun <T> create(service: Class<T>): T {
        return Proxy.newProxyInstance(service.classLoader, arrayOf<Class<*>>(service), object : InvocationHandler {
            // ⚠️ InvocationHandler 不能使用lambda表达式，因为args可能会空
            override fun invoke(proxy: Any, method: Method, args: Array<out Any>?): Any {
                var methodParser = methodService[method]
                if (methodParser == null) {
                    methodParser = MethodParser.parse(baseUrl, method)
                    methodService[method] = methodParser
                }
                val request = methodParser.genericNewRequestInfo(method, args)
                return scheduler!!.newCall(request)
            }
        }) as T
    }
}